<?php

namespace common\services\myhtsq;

use Yii;
use common\entities\myhtsq\InvoiceEntity;
use common\support\ExcelManage;
use common\error\ErrorCode;
use common\error\ErrorInfo;
use common\repositories\myhtsq\ContractEmailContactsRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\repositories\myhtsq\ErpUserRepository;
use common\services\BaseService;
use common\entities\ConfigEntity;
use common\models\myhtsq\DocumentModel;
use common\repositories\myhtsq\InvoiceRepository;
use common\repositories\myhtsq\InvoiceSummaryRepository;
use common\repositories\myhtsq\InvoiceReceivableRepository;
use common\repositories\myhtsq\InvoicePaymentRepository;
use common\repositories\myhtsq\DocumentRepository;
use common\repositories\myhtsq\ContractReceivableRepository;
use common\repositories\myhtsq\SpecialApprovalInvoiceRepository;
use common\repositories\myhtsq\InvoiceBusinessUnitRepository;
use common\services\common\EmailService;
use common\services\myhtsq\DocumentService;
use common\support\StringHelper;
use PHPExcel_Shared_Date;
use yii\base\Exception;

/**
 * Description of InvoiceService
 * 发票管理服务
 * @author chenxc
 */
class InvoiceService extends BaseService
{

    protected $_invoiceRepository;

    public function __construct(InvoiceRepository $invoiceRepository)
    {
        $this->_invoiceRepository = $invoiceRepository;
    }

    /**
     * 发票管理模块：获取发票列表信息，支持分页
     * @param int $isMainInvoice 是否主发票
     * @param int $invoiceStatus 发票状态
     * @param int $invoiceBeginDate 开票开始日期
     * @param date $invoiceEndDate 开票结束日期
     * @param date $searchKey 查询关键字
     * @param int $pageIndex 页索引
     * @param int $pageSize 页大小
     * @return array PageResult
     */
    public function getInvoiceListByPage($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $pageIndex, $pageSize)
    {
        $areaId = $this->filterBusinessUnit(\Yii::$app->user->identity);

        $signPeopleId = $this->getSignPeopleId(\Yii::$app->user->identity);

        return $this->_invoiceRepository->getInvoiceListByPage($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $pageIndex, $pageSize, $areaId, $signPeopleId);
    }

    public function getSignPeopleId($user)
    {
        $signPeopleId = '';
        $userEntity = ErpInterfaceService::getUserByCode($user->usercode);
        if ($userEntity->OnlyViewMyself) {
            $signPeopleId = $user->userguid;
        }

        return $signPeopleId;
    }

    public function filterBusinessUnit($user)
    {
        $userEntity = ErpInterfaceService::getUserByCode($user->usercode);
        #显示全部区域数据
        if ($userEntity->ViewAllArea) {
            return '';
        }
        return ErpInterfaceService::getSubBuGuidsByBuGuid($userEntity->BUGUID);
    }

    /**
     * 保存发票
     * @param $invoiceModel
     * @return boolean|string   失败|发票Guid
     */
    public function saveInvoice($invoiceModel)
    {
        if ($invoiceModel->validate()) {
//            if (self::exitSameInvoiceCode($invoiceModel->invoice_code, $invoiceModel->invoice_id)) {
//                return self::setAndReturn(ErrorCode::ERR_INVOICE_CODE_EXIST_SAME);
//            }

            if ($invoiceModel->is_red_invoice != 1 && self::exitSameInvoiceNo($invoiceModel->invoice_no, $invoiceModel->invoice_id)) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_NO_EXIST_SAME);
            }

            // 开启事务
            $configDataBase = ConfigEntity::getDb();
            $trans = $configDataBase->beginTransaction();

            if (isset($invoiceModel->invoice_id) && !empty($invoiceModel->invoice_id)) {
                //修改
                $result = InvoiceRepository::updateInvoice($invoiceModel);
            } else {
                //新增
                $result = InvoiceRepository::addInvoice($invoiceModel);
            }

            if ($result === false) {
                // 回滚事务
                $trans->rollBack();
                return self::setAndReturn(InvoiceRepository::getErrCode());
            } else {
                // 先删除原有的发票摘要
                $res = InvoiceSummaryRepository::deleteInvoiceSummaryByInvoiceId($result);
                if ($res !== true) {
                    // 回滚事务
                    $trans->rollBack();
                    return self::setAndReturn(InvoiceSummaryRepository::getErrCode());
                }

                // 再新增现有的发票摘要
                $invoiceSummarys = $invoiceModel->invoiceSummarys;
                if (count($invoiceSummarys) > 0) {
                    foreach ($invoiceSummarys as $k => $v) {
                        $v['invoice_id'] = $result;
                        $v['summary_id'] = null;
                        $res = InvoiceSummaryRepository::addInvoiceSummary($v);
                        if ($res === false) {
                            // 回滚事务
                            $trans->rollBack();
                            return self::setAndReturn(InvoiceSummaryRepository::getErrCode());
                        }
                    }
                }

                // 保存文档记录
                $invoiceDocuments = $invoiceModel->invoiceDocuments;
                if (isset($invoiceDocuments) && count($invoiceDocuments) > 0) {
                    foreach ($invoiceDocuments as $k => $v) {
                        if (!isset($v ['__type'])) {
                            $v ['__type'] = 'update';
                        }
                        switch ($v ['__type']) {
                            case 'delete' :
                                $res = DocumentRepository::delDocumentById($v['document_id']);
                                if ($res === false) {
                                    // 回滚事务
                                    $trans->rollBack();
                                    return self::setAndReturn(DocumentRepository::getErrCode());
                                }
                                break;
                            case 'add' :
                                $documentModel = new DocumentModel();
                                $documentModel->setAttributes($v);
                                $explode = explode('.', $v['document_name']);
                                $extName = end($explode);
                                $documentModel->document_ext_name = $extName;
                                $documentModel->business_id = $result;
                                if ($documentModel->validate()) {
                                    $newdoc = new DocumentRepository();
                                    $newdoc->addDocument($documentModel);
                                    if ($res === false) {
                                        // 回滚事务
                                        $trans->rollBack();
                                        return self::setAndReturn(DocumentRepository::getErrCode());
                                    }
                                }
                                break;
                        }
                    }
                }

                // 提交事务
                $trans->commit();

                return $result;
            }
        } else {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_VERIFY_FAIL);
        }
    }

    /**
     * 根据发票ID删除对应的发票信息
     * @param string $invoiceId 发票ID
     * @param boolean $fromContract 来自合同模块中的删除
     * @return boolean 返回true时表示删除成功，否则失败
     */
    public function deleteInvoice($invoiceId, $fromContract = false)
    {
        $invoiceEntity = InvoiceRepository::getInvoiceEntity($invoiceId);

        if (!isset($invoiceEntity)) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_NOT_EXISTS);
        }

        if (isset($invoiceEntity->red_by_invoice_id)) {
            return ErrorInfo::setAndReturn(ErrorCode::ERR_INVOICE_DELETE_FAIL, '', '被红冲发票，不允许删除');
        }

        if (intval($invoiceEntity->is_red_invoice) === 1) {
            return ErrorInfo::setAndReturn(ErrorCode::ERR_INVOICE_DELETE_FAIL, '', '红冲发票，不允许删除');
        }

        if (!$fromContract) {
            if (isset($invoiceEntity['receivables_amount']) && floatval($invoiceEntity['receivables_amount']) > 0) {
                return ErrorInfo::setAndReturn(ErrorCode::ERR_INVOICE_DELETE_FAIL, '', '发票已经关联了应收款，不允许删除');
            }
        }

        if (isset($invoiceEntity['payment_amount']) && floatval($invoiceEntity['payment_amount']) > 0) {
            return ErrorInfo::setAndReturn(ErrorCode::ERR_INVOICE_DELETE_FAIL, '', '发票已经关联了回款，不允许删除');
        }

        // 开启事务
        $configDataBase = ConfigEntity::getDb();
        $trans = $configDataBase->beginTransaction();

        $result = InvoiceRepository::deleteInvoice($invoiceId);
        if ($result !== true) {
            $trans->rollBack();
            return self::setAndReturn(InvoiceRepository::getErrCode());
        }

        // 删除发票摘要
        $result = InvoiceSummaryRepository::deleteInvoiceSummaryByInvoiceId($invoiceId);
        if ($result !== true) {
            $trans->rollBack();
            return self::setAndReturn(InvoiceSummaryRepository::getErrCode());
        }

        // 删除特批发票
        $specialApprovalInvoiceService = new SpecialApprovalInvoiceService(new SpecialApprovalInvoiceRepository());
        $result = $specialApprovalInvoiceService->delSpecialApprovalInvoiceByInvoiceNumber($invoiceEntity['invoice_no']);
        if ($result === FALSE) {
            $trans->rollBack();
            return self::setAndReturn($specialApprovalInvoiceService::getErrCode());
        }

        if ($fromContract) {
            $receivableIds = [];
            // 获取 发票与应收款对应关系记录
            $invoiceReceivables = InvoiceReceivableRepository::getInvoiceReceivablesByInvoiceId($invoiceId);
            if (isset($invoiceReceivables) && count($invoiceReceivables) > 0) {
                foreach ($invoiceReceivables as $k => $v) {
                    if (isset($v['receivable_id']) && !empty($v['receivable_id']) && !in_array($v['receivable_id'], $receivableIds)) {
                        $receivableIds[] = $v['receivable_id'];
                    }
                }
            }

            $res = InvoiceReceivableRepository::deleteInvoiceReceivableByInvoiceId($invoiceId);
            if (!$res) {
                $trans->rollBack();
                return self::setAndReturn(ErrorCode::ERR_INVOICE_DELETE_FAIL);
            }

            foreach ($receivableIds as $k => $v) {
                // 根据应收款ID重新刷新应收款的billing_amount
                $res = ContractReceivableService::summaryReceivablesAmount($v);
                if (!$res) {
                    $trans->rollBack();
                    return self::setAndReturn(ErrorCode::ERR_INVOICE_DELETE_FAIL);
                }
            }
        }

        $trans->commit();

        return true;
    }

    /**
     * 根据发票ID设置当前发票成遗失状态
     * @param string $invoiceId 发票ID
     * @return boolean 返回true时表示设置成功，否则失败
     */
    public function doLose($invoiceId)
    {
        if (!InvoiceRepository::isExistInvoice($invoiceId)) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_NOT_EXISTS);
        }

        // 开启事务
        $configDataBase = ConfigEntity::getDb();
        $trans = $configDataBase->beginTransaction();

        $result = InvoiceRepository::doLose($invoiceId);
        if ($result !== true) {
            $trans->rollBack();
            return self::setAndReturn(InvoiceRepository::getErrCode());
        }

        $receivableIds = [];
        $invoiceReceivables = InvoiceReceivableRepository::getInvoiceReceivablesByInvoiceId($invoiceId);
        if (isset($invoiceReceivables) && count($invoiceReceivables) > 0) {
            foreach ($invoiceReceivables as $k => $v) {
                $receivableIds[] = $v['receivable_id'];
                // 2、删除myscrm_invoice_payment对应的记录
                $result = InvoicePaymentRepository::deleteInvoicePaymentByInvoiceReceivableId($v['invoice_receivable_id']);
                if (!$result) {
                    $trans->rollBack();
                    return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL);
                }
            }
        }

        // 3、删除myscrm_invoice_receivable对应的记录
        $result = InvoiceReceivableRepository::deleteInvoiceReceivableByInvoiceId($invoiceId);
        if (!$result) {
            $trans->rollBack();
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL);
        }

        // 4、更新合同应收款中的billing_amount、received_amount
        foreach ($receivableIds as $k => $v) {
            $contractReceivableEntity = ContractReceivableRepository::getContractReceivableById($v);
            if (isset($contractReceivableEntity)) {
                $billingAmount = InvoiceReceivableRepository::getTotalBillingAmountByReceivableId($v);
                $receivedAount = InvoicePaymentRepository::getTotalPaymentAmountByReceivableId($v);

                $contractReceivableEntity->billing_amount = $billingAmount;
                $contractReceivableEntity->received_amount = $receivedAount;
                $result = $contractReceivableEntity->update();
                if ($result === false) {
                    $trans->rollBack();
                    return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL);
                }
            }
        }

        $trans->commit();
        return true;
    }

    /**
     * 根据发票ID获取发票信息
     * @param string $invoiceId
     * @return array
     */
    public function getInvoiceInfo($invoiceId)
    {
        $invoice = InvoiceRepository::getInvoiceInfo($invoiceId);
        $summarys = InvoiceSummaryRepository::getInvoiceSummarysByInvoiceId($invoiceId);
        $invoiceDocuments = DocumentService::getDocumentListByBusinessId($invoiceId);

        $invoice['invoiceSummarys'] = $summarys;
        $invoice['invoiceDocuments'] = $invoiceDocuments;

        return $invoice;
    }

    /**
     * 根据合同ID获取对应的发票信息
     * @param string $contractId
     * @return array
     */
    public function getInvoiceListByContractId($contractId)
    {
        $invoices = InvoiceRepository::getInvoiceListByContractId($contractId);
        if (isset($invoices) && count($invoices) > 0) {
            foreach ($invoices as $k => $v) {
                $main_invoice_no = '';
                if ($v['is_child_invoice'] == 1 && !empty($v['main_invoice_id'])) {
                    $mainInvoice = InvoiceRepository::getInvoiceEntity($v['main_invoice_id']);
                    if (isset($mainInvoice)) {
                        $main_invoice_no = $mainInvoice['invoice_no'];
                    }
                }
                $invoices[$k]['main_invoice_no'] = $main_invoice_no;

                $summarys = InvoiceSummaryRepository::getInvoiceSummarysByInvoiceId($v['invoice_id']);
                $invoices[$k]['invoiceSummarys'] = $summarys;
            }
        }

        return $invoices;
    }

    public function getInvoiceReceivable($invoiceId)
    {
        return InvoiceRepository::getInvoiceReceivable($invoiceId);
    }

    /**
     * 特批界面获取发票select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $limit 只显示几条记录
     */
    public static function getInvoiceListForSepcialInvoiceSelect2($keyword, $limit)
    {
        return InvoiceRepository::getInvoiceListForSepcialInvoiceSelect2($keyword, $limit);
    }

    /**
     * 根据发票ID重新刷新发票的receivables_amount
     * @param type $invoiceId
     * @return boolean true刷新成功/false刷新失败
     */
    public static function summaryReceivablesAmount($invoiceId)
    {
        $totalAmount = 0;
        $invoice = InvoiceRepository::getInvoiceEntity($invoiceId);
        if (!isset($invoice)) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_NOT_EXISTS);
        }

        $invoiceReceivables = InvoiceReceivableRepository::getInvoiceReceivablesByInvoiceId($invoiceId);
        if (isset($invoiceReceivables) && count($invoiceReceivables) > 0) {
            foreach ($invoiceReceivables as $k => $v) {
                $totalAmount += floatval($v['cur_billing_amount']);
            }
        }

        $invoice->receivables_amount = $totalAmount;
        $invoice->modified_on = ConfigEntity::getDbNowDate();
        $result = $invoice->update();

        if ($result === false) {
            return $result;
        }

        return true;
    }

    /**
     * 重新刷新发票的回款金额
     * @param string $invoiceId 发票ID
     * @return boolean true刷新成功/false刷新失败
     */
    public static function summaryInvoicePaymentAmount($invoiceId)
    {
        $invoice = InvoiceRepository::getInvoiceEntity($invoiceId);
        if (!isset($invoice)) {
            return false;
        }

        $totalPaymentAmount = InvoicePaymentRepository::getTotalPaymentAmountByInvoiceId($invoiceId);
        $invoice->payment_amount = $totalPaymentAmount;
        $invoice->modified_on = ConfigEntity::getDbNowDate();
        $affectedRowNum = $invoice->update();
        if ($affectedRowNum === false) {
            return false;
        }

        return true;
    }

    /**
     * 获取可以作为父级发票的发票信息
     * @param string $keyword
     * @return array
     */
    public function getParentInvoiceInfo($keyword)
    {
        return InvoiceRepository::getParentInvoiceInfo($keyword);
    }

    /**
     * 根据发票id获取发票的entity对象
     * @param string $invoiceId 发票ID
     * @return InvoiceEntity
     */
    public static function getInvoiceEntity($invoiceId)
    {
        return InvoiceRepository::getInvoiceEntity($invoiceId);
    }

    /**
     * 获取所有可以被引用的发票信息
     * @param string $contractId
     * @return array
     */
    public function getCanUseInvoiceInfo($contractId = null, $keyword = null)
    {
        $result = InvoiceRepository::getCanUseInvoiceInfo($contractId, $keyword);
        return $result;
    }

    /**
     * 检查是否存在相同发票代码的发票
     * @param string $invoiceCode 发票代码
     * @param string $invoiceId 发票id
     * @return boolean true存在/false不存在
     */
    public static function exitSameInvoiceCode($invoiceCode, $invoiceId = null)
    {
        return InvoiceRepository::exitSameInvoiceCode($invoiceCode, $invoiceId);
    }

    /**
     * 检查是否存在相同发票编号的发票
     * @param string $invoiceNo 发票编号
     * @param string $invoiceId 发票id
     * @return boolean true存在/false不存在
     */
    public static function exitSameInvoiceNo($invoiceNo, $invoiceId = null)
    {
        return InvoiceRepository::exitSameInvoiceNo($invoiceNo, $invoiceId);
    }

    /**
     * 判断主发票的开票金额是否不小于所有子发票的开票金额
     * @param string $mainInvoiceId
     * @return boolean true校验通过，false校验不通过
     */
    public static function checkMainInvoiceAmountMorethanChildAmount($mainInvoiceId)
    {
        $parentInvoice = InvoiceRepository::getInvoiceEntity($mainInvoiceId);
        if (isset($parentInvoice)) {
            $parentInvoiceAmount = $childInvoiceAmount = 0;
            if (isset($parentInvoice['invoice_amount']) && !empty($parentInvoice['invoice_amount'])) {
                $parentInvoiceAmount = floatval($parentInvoice['invoice_amount']);
            }

            $childInvoices = InvoiceRepository::getChildInvoiceInfo($mainInvoiceId);
            if (isset($childInvoices) && count($childInvoices) > 0) {
                foreach ($childInvoices as $k => $v) {
                    if (isset($v['invoice_amount']) && !empty($v['invoice_amount'])) {
                        $childInvoiceAmount += floatval($v['invoice_amount']);
                    }
                }
            }

            return $parentInvoiceAmount >= $childInvoiceAmount;
        }

        return true;
    }

    /**
     * 获取开票单位
     * @param string $keyword 搜索关键字
     * @return array
     */
    public function getInvoiceBusinessUnit($keyword = '')
    {
        return InvoiceBusinessUnitRepository::getInvoiceBusinessUnit($keyword);
    }

    /**
     * 过期未全部回款的发票发送提醒
     */
    public function invoiceExpiredRemind()
    {
        $expiredDate = date_add(date_create_from_format('Y-m-d H:i:s', ConfigEntity::getDbNowDate()), \DateInterval::createFromDateString('-7 Day'));
        $expiredDate = date_format($expiredDate, 'Y-m-d');
        //获取开票七天仍未回完款发票
        $expiredInvoices = InvoiceRepository::getExpiredInvoices($expiredDate);
        foreach ($expiredInvoices as $key => $item) {
            //获取合同信息
            $contractInfo = ContractManageRepository::getContractManageModelByContractId($item['contract_id']);
            //获取发票对应的未回完款的应收
            $noReceived = ContractReceivableRepository::getNoReceivedByInvoice($item['invoice_id']);
            foreach ($noReceived as $key2 => $item2) {
                $emailParams = [
                    'contractId' => $contractInfo->contract_code,
                    'custName' => $contractInfo->customer_name,
                    'invoiceAmount' => $item2['billing_amount'],
                    'remainAmount' => ($item2['billing_amount'] - $item2['received_amount']) . '(发票'
                        . $item['invoice_amount'] . ',绑定应收' . $item2['billing_amount'] . ',绑定回款' . $item2['received_amount'] . ')',
                    'invoiceDate' => $item['invoice_date']
                ];
                $this->sendEmail($item2['payee_id'], '【合同管理】已开票未全部回款', 'invoiceExpired', $emailParams, []);
            }
        }
    }

    private function sendEmail($userId, $subject, $template, $params, $cc)
    {
        $user = ErpUserRepository::getUserById($userId);
        if (empty($user)) {
            return;
        }
        //获取抄送人
        $copyToEMail = ContractEmailContactsRepository::getCCContactsByBu($user['BUGUID'], $user['UserCode']);

        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];
        $params['userName'] = $user['UserName'];

        if (is_array($cc)) {
            $copyToEMail = array_merge($copyToEMail, $cc);
        }
        $params['ScrmUrl'] = \Yii::$app->params['ScrmUrl'];
        return EmailService::sendEMail([$user['Email'] => $user['UserName']], $subject, 'contract/' . $template, $params, $copyToEMail);
    }

    /**
     *
     * 发票管理模块：获取发票列表信息，支持分页
     * @param int $isMainInvoice 是否主发票
     * @param int $invoiceStatus 发票状态
     * @param int $invoiceBeginDate 开票开始日期
     * @param date $invoiceEndDate 开票结束日期
     * @param date $searchKey 查询关键字
     * @param int $pageIndex 页索引
     * @param int $pageSize 页大小
     * @return array PageResult
     */
    public function exportInvoiceListExecl($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $pageIndex, $pageSize)
    {
        $areaId = $this->filterBusinessUnit(\Yii::$app->user->identity);
        $data = $this->_invoiceRepository->getInvoiceListByPage($isMainInvoice, $invoiceStatus, $invoiceBeginDate, $invoiceEndDate, $searchKey, $pageIndex, $pageSize, $areaId);

        $objPHPExcel = new \PHPExcel();
        //设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('Simple');

        //设置单元格的值
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '开票单位');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '开票单位');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '发票类别');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '发票代码');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '发票号码');
        $objPHPExcel->getActiveSheet()->setCellValue('F1', '开票日期');
        $objPHPExcel->getActiveSheet()->setCellValue('G1', '开通金额');
        $objPHPExcel->getActiveSheet()->setCellValue('H1', '已回款金额');
        $objPHPExcel->getActiveSheet()->setCellValue('I1', '未回款金额');
        $objPHPExcel->getActiveSheet()->setCellValue('J1', '是否红冲');
        $objPHPExcel->getActiveSheet()->setCellValue('K1', '摘要');
        $objPHPExcel->getActiveSheet()->setCellValue('L1', '客户名称');
        $objPHPExcel->getActiveSheet()->setCellValue('M1', '签约客户全称');
        $objPHPExcel->getActiveSheet()->setCellValue('N1', '合同编号');
        $objPHPExcel->getActiveSheet()->setCellValue('O1', '发票类型');
        $objPHPExcel->getActiveSheet()->setCellValue('P1', '合同所属区域');
        $objPHPExcel->getActiveSheet()->setCellValue('Q1', '申请人');
        $objPHPExcel->getActiveSheet()->setCellValue('R1', '是否有合同');
        $objPHPExcel->getActiveSheet()->setCellValue('S1', '备注');

        if (!empty($data['items'])) {
            $j = 2;
            foreach ($data['items'] as $key => $val) {
                $i = 'A';
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoiceCompanyName']); // 开票单位
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoiceCompanyName']); // 开票单位
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_category'] == 1 ? "服务票" : "销售票"); //发票类别
                $i++;
                //$objPHPExcel->getActiveSheet()->setCellValue($i . $j, ''.$val['invoice_code']); //发票代码
                $objPHPExcel->getActiveSheet()->getStyle($i . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                $objPHPExcel->getActiveSheet()->setCellValueExplicit($i . $j, $val['invoice_code'], \PHPExcel_Cell_DataType::TYPE_STRING);
                $i++;
                //$objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_no']); //发票号码
                $objPHPExcel->getActiveSheet()->getStyle($i . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                $objPHPExcel->getActiveSheet()->setCellValueExplicit($i . $j, $val['invoice_no'], \PHPExcel_Cell_DataType::TYPE_STRING);
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, date('Y-m-d', strtotime($val['invoice_date']))); //开票日期
                $objPHPExcel->getActiveSheet()->getStyle($i . $j)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2);
                //$objPHPExcel->getActiveSheet()->setCellValue($i . $j, \PHPExcel_Shared_Date::PHPToExcel(date('Y-m-d', strtotime($val['invoice_date'])))); //开票日期
                //$objPHPExcel->getActiveSheet()->setCellValueExplicit($i . $j, \PHPExcel_Shared_Date::PHPToExcel(date('Y/m/d', strtotime($val['invoice_date']))), \PHPExcel_Cell_DataType::TYPE_NUMERIC);
                //$tempArray[] = gmdate("Y-m-d H:i:s", \PHPExcel_Shared_Date::ExcelToPHP($objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue()));   
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_amount']); //开通金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['payment_amount']); //已回款金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_amount'] - $val['payment_amount']); //未回款金额
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['is_red_invoice'] == '1' ? '是' : '否'); //是否红冲
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['summary_type']); //摘要
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['customer_name']); //客户名称
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['customer_full_name']); //签约客户全称
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['contractCode']); //合同编号
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_type'] == "0" ? "增值税普通发票" : "增值税专用发票"); //发票类型
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['area_name']); //合同所属区域
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['invoice_proposer']); //申请人
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['is_havecontract'] == '1' ? '是' : '否'); //是否有合同
                $i++;
                $objPHPExcel->getActiveSheet()->setCellValue($i . $j, $val['remark']); //备注
                $j++;
            }
        }

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setVisible(false); //把合同guid 设置为隐藏列
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="发票清单' . date("YmdHis") . '.xls"');
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 导入发票
     * @return bool|int|string
     */
    public function importInvoiceListExecl(){
        if (empty($_FILES ['file'])) {
            return $this->setAndReturn(-1, '', '上传文件不能为空');
        }
        $filename = explode('.', $_FILES ['file']['name']);
        if ($filename [1] != 'xls' && $filename [1] != 'xlsx') {
            return $this->setAndReturn(-1, '', '请上传EXCEL文件');
        }

        $import_data = ExcelManage::importDataByFilePath($_FILES['file']['tmp_name'], 2);

        if (empty($import_data)) {
            return $this->setAndReturn(-1, '', 'EXCEL文件无数据');
        }

        $invoice_data = [];
        $invoice_summary_data = [];
        $invoice_codes = [];
        foreach ($import_data as $data) {
            $data = implode(',', $data);
            list(
                $import['invoice_company_name'],
                $import['invoice_date'],
                $import['invoice_type'],
                $import['invoice_category'],
                $import['invoice_code'],
                $import['invoice_no'],
                $import['customer_name'],
                $import['summary_type'],
                $import['summary_amount'],
                $import['invoice_amount'],
                $import['contract_code'],
                $import['proposer_name']
                ) = \explode(',', $data);

            $invoice_id = StringHelper::uuid();
            $import['invoice_id'] = $invoice_id;

            if(empty($import['invoice_code']) || empty($import['invoice_no'])){
                continue;
            }

            if(!empty(InvoiceRepository::getInvoiceInfoByCode($import['invoice_code'],$import['invoice_no']))){
                $message = '发票代码:'.$import['invoice_code'].' 发票编号:'.$import['invoice_no'].' 的发票已存在,不允许导入,请检查修正!';
                return $this->setAndReturn(-1, $message, $message);
            }

            if(empty($import['invoice_type'])){
                $import['invoice_type'] = '0';
            }else {
                $import['invoice_type'] = \Yii::$app->params['invoice_type'][$import['invoice_type']];
            }
            $import['invoice_category'] = \Yii::$app->params['invoice_category'][$import['invoice_category']];

            $import['invoice_date'] = date('Y-m-d H:i:s', PHPExcel_Shared_Date::ExcelToPHP($import['invoice_date']));

            $import['invoice_amount'] = empty($import['invoice_amount'])?0:$import['invoice_amount'];

            $contracts = ContractManageRepository::getContractByContractCode($import['contract_code']);
            if(empty($contracts)){
                $message = '合同编码:'.$import['contract_code'].'  匹不到对应的合同信息,请检查核对!';
                return $this->setAndReturn(-1, $message, $message);
            }
            $import['contract_id'] = ContractManageRepository::getContractByContractCode($import['contract_code'])[0]['contract_id'];

            $import['proposer_id'] = ErpUserRepository::getUserGUIDByUserName($import['proposer_name']);

            $import['invoice_company_id'] = InvoiceBusinessUnitRepository::getInvoiceBusinessUnitByBUName($import['invoice_company_name'])['BUGUID'];

            if (empty($import['invoice_company_id'])) {
                $message = '导入的excel文件中的开票单位 "'. $import['invoice_company_name'] . '" 有误,匹配不到数据,请检查';
                return $this->setAndReturn(-1, $message, $message);
            }

            $import['remark'] = "手工批量导入数据,导入人:".Yii::$app->user->getIdentity()->username." 时间:".ConfigEntity::getDbNowDate();

            $invoice_summary_data[] = [
                'summary_id'=>StringHelper::uuid(),
                'summary_type'=>$import['summary_type'],
                'summary_amount'=>$import['summary_amount'],
                'invoice_id'=>$invoice_id
            ];

            unset($import['proposer_name'], $import['invoice_company_name'],$import['contract_code'],$import['summary_type'],$import['summary_amount']);

            $invoice_data[] = $import;


            // 发票代码合集
            $invoice_codes[] = empty($import['invoice_code'])?'':$import['invoice_code'];
        }

        if (empty($invoice_data)) {
            return $this->setAndReturn(-1, '', 'EXCEL文件无数据');
        }

        //暂时不要直接删除
        //InvoiceRepository::delInvoiceBatch($invoice_codes);

        // insert into db
        $result = InvoiceRepository::addInvoiceBatch($invoice_data);
        if($result === false){
            return false;
        }else{
            $result = InvoiceSummaryRepository::addInvoiceSummaryBatch($invoice_summary_data);
            if($result === false){
                return false;
            }
        }
        return $result;



    }

    /**
     * 根据发票id获取发票信息
     * @param type $contractId
     * @return type
     */
    public function getInvoiceInfoById($invoiceId)
    {
        return InvoiceRepository::getInvoiceInfoById($invoiceId);
    }
}
